const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../config/config.default')
const { tokenExpiredError, invalidToken, hadNotAdminPermission } = require('../consitan/err.type')
const auth = async (ctx, next) => {
    const { authorization = '' } = ctx.request.header
    console.log(authorization)
    const token = authorization.replace('Bearer ', '')
    try {
        ctx.state.user = jwt.verify(token, JWT_SECRET)
    } catch (err) {
        switch (err.name) {
            case 'TokenExpiredError':
                console.error('token过期', err)
                return ctx.app.emit('error', tokenExpiredError, ctx)
            case 'JsonWebTokenError':
                console.error('无效的token', err)
                return ctx.app.emit('error', invalidToken, ctx)
            default:
                break
        }
    }
    await next()
}
const hadAdminPermission = async (ctx, next) => {
    const {isAdmin} = ctx.state.user
    if(!isAdmin) {
        console.error('该用户没有管理员权限', ctx.state.user)
        return ctx.app.emit('error', hadNotAdminPermission, ctx)
    }
    await next()
}
module.exports = {
    auth,
    hadAdminPermission
}